package com.peng.leetcode.list;

/**
 * ReverseBetween
 * <p>
 * 92. 反转链表 II
 *
 * @author: lupeng6
 * @create: 2021/3/19 10:20
 */
public class ReverseBetween {

    public static void main(String[] args) {
        ListNode listNode = BuildListNode.tailInsert(1, 2, 3, 4, 5);
        ListNode listNode1 = new ReverseBetween().reverseBetween(listNode, 2, 4);
        System.out.println(listNode1);
    }


    public ListNode reverseBetween(ListNode head, int left, int right) {
        int index = 0;
        ListNode dummy = new ListNode(0);
        ListNode curr = dummy;
        while (index < left - 1) {
            curr.next = head;
            curr = curr.next;
            head = head.next;
            index++;
        }

        ListNode newHead = null;
        ListNode tail = null;
        // reverse
        while (index < right) {
            if (tail == null) {
                tail = head;
            }
            ListNode temp = head.next;
            head.next = newHead;
            newHead = head;
            head = temp;
            index++;
        }
        curr.next = newHead;
        curr = tail;

        while (head != null) {
            curr.next = head;
            curr = curr.next;
            head = head.next;
        }

        return dummy.next;
    }

}
